package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entity.CommonResult;
import com.atguigu.springcloud.entity.Payment;
import com.atguigu.springcloud.lb.LoadBalancer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * 使用restTemplate调用接口
 *
 * @author Tu
 * @date 2022/11/20 20:33
 */
@Slf4j
@RestController
public class OrderController {

    /**
     * 微服务调用，服务提供者微服务名称
     */
    //private static final String PAYMENT_URL = "http://localhost:8001";
    private static final String PAYMENT_URL = "http://cloud-eureka-provider";

    @Resource
    private RestTemplate restTemplate;
    /**
     * 自定义负载均衡
     */
    @Resource
    private LoadBalancer loadBalancer;
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/consumer/payment/selectById/{id}")
    public CommonResult<Payment> selPaymentById(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/api/v1/payment/selById/" + id, CommonResult.class);
    }

    @GetMapping(value = "/consumer/payment/create")
    public CommonResult<Payment> insertPayment(@RequestBody Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/api/v1/payment/insert", payment, CommonResult.class);
    }

    @PostMapping(value = "/consumer/payment/selectByIdForEntity")
    public CommonResult selPaymentByIdForEntity(@RequestBody String id) {
        ResponseEntity<CommonResult> resultResponseEntity = restTemplate.getForEntity(PAYMENT_URL + "/api/v1/payment/selById/" + id, CommonResult.class);
        //返回响应结果集可以用来判断响应码
        if (resultResponseEntity.getStatusCode().is2xxSuccessful()) {
            return resultResponseEntity.getBody();
        } else {
            return new CommonResult<>(resultResponseEntity.getStatusCode().value(), resultResponseEntity.getStatusCode().getReasonPhrase());
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = "/payment/consumer/serverPort")
    public String getPaymentLb() {
        //通过微服务名称获取服务集群
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-eureka-provider");
        if (CollectionUtils.isEmpty(instances)) {
            return "获取提供者服务为空";
        }
        ServiceInstance serviceInstance = loadBalancer.getServiceInstance(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri + "/api/v1/payment/serverPort", String.class);
    }

}
